<template>
  <div class="address">
    <div class="header">
      <van-nav-bar
        title="确认订单"
        left-text="返回"
        left-arrow
        @click-left="$router.back()"
      />
    </div>
    <div class="default">
      <van-address-list v-if="flag"
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        add-button-text="添加地址"
        @click-item="clickItem"
        @add="onAdd"
        @edit="onEdit"
      />
      <van-button v-else type="primary" @click="changeGo" block round style="margin-top: 30px">新增地址</van-button>
    </div>
    <div class="another"></div>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  Toast,
  AddressList,
  Button,
  NavBar
} from 'vant'

import { defaultAddress, findAddress } from '@/api/order'

Vue.use(Toast)
Vue.use(AddressList)
Vue.use(Button)
Vue.use(NavBar)

export default {
  data () {
    return {
      flag: false,
      chosenAddressId: '1',
      list: []
    }
  },
  methods: {
    onAdd () {
      Toast('新增地址')
      this.$router.push('/order/' + this.$route.params.time + '/addAddress1')
    },
    changeGo () {
      this.$router.push('/order/' + this.$route.params.time + '/addAddress1')
    },
    onEdit (item, index) {
      Toast('编辑地址:' + index)
    },
    clickItem (item) {
      localStorage.setItem('Addresss', item.address)
      localStorage.setItem('Name', item.name)
      localStorage.setItem('Tel', item.tel)
      this.$router.back()
    }
  },
  mounted () {
    defaultAddress({
      token: localStorage.getItem('token'),
      userid: localStorage.getItem('userid')
    })
    findAddress({ userid: localStorage.getItem('userid') }).then(res => {
      if (res.data.data.length !== 0) {
        this.flag = true
      }
      console.log(res.data.data)
      var i = 0
      this.list = res.data.data.map((item) => {
        item.id = ++i
        item.address = item.province + item.city + item.county + item.addressDetail
        return item
      }).sort((a, b) => {
        return b.isDefault - a.isDefault
      })
    })
  }
}
</script>
